import { GoogleGenerativeAI } from '@google/generative-ai';
import { Injectable } from '@nestjs/common';
import axios from 'axios';

class CommandProcessor {
  private commandPrefix: string;
  private gemini_api_key = process.env.GEMINI_AI_API_KEY;
  private gen_ai = new GoogleGenerativeAI(this.gemini_api_key);
  private model = this.gen_ai.getGenerativeModel({ model: 'gemini-1.5-flash' });
  constructor(commandPrefix: string) {
    this.commandPrefix = commandPrefix;
  }

  public getAnswer(command: string): string | null {
    if (command.startsWith(this.commandPrefix)) {
      const [commandName, ...commandBodyParts] = command
        .slice(this.commandPrefix.length)
        .split(' ');
      const commandBody = commandBodyParts.join(' ');

      const method = (this as any)[commandName];
      if (typeof method === 'function') {
        return method.call(this, commandBody);
      }
    }
    return null;
  }
  // комманда для получения рандомного числа
  private rand(body: string) {
    if (body.length !== 0) {
      let nums = body.split(' ').map((num) => Number(num));
      if (nums.length === 1) {
        if (!Number.isNaN(nums[0])) {
          return (
            '[ Рандомное число: ' +
            String(Math.floor(Math.random() * (nums[0] - 1) + 1)) +
            ' ]'
          );
        }
      }
      if (nums.length === 2) {
        if (!Number.isNaN(nums[0])) {
          return (
            '[ Рандомное число: ' +
            String(Math.floor(Math.random() * (nums[1] - nums[0]) + nums[0])) +
            ' ]'
          );
        }
      }
    }
    return '[\nОшибка неверный синтаксис.\nПример применения:\n\t\t/rand {max}\n\t\t/rand {min} {max}\n]';
  }
  // комманда эхо
  private echo(body: string): string {
    if (body.length === 0) {
      return 'Ошибка неверный синтаксис.\n Пример применения:\n\t\t/echo {строка}';
    }
    return `[ ${body} ]`;
  }
  // работа с gemini
  private async $(body: string) {
    const result = await this.model.generateContent(
      body + ' ПИШИ ответ в формате MARKDOWN TELEGRAM',
    );
    const response = await result.response;
    const text = await response.text();
    return 'Г:' + text;
  }
}

@Injectable()
export class TelegramService {
  private processor = new CommandProcessor('/');
  private bot_token = process.env.TELEGRAM_API_KEY;
  private url = `https://api.telegram.org/bot${this.bot_token}/sendMessage`;

  async MessageHandler(chat_id: number, msg: string, thread_id: number) {
    const result = await this.processor.getAnswer(msg);
    if (result) {
      return await this.SendMessage(chat_id, result, thread_id);
    }
  }

  async SendMessage(chat_id: number, msg: string, thread_id: number) {
    await axios.post(this.url, {
      chat_id: chat_id,
      message_thread_id: thread_id,
      text: msg,
    });
  }
}
